package com.ilancuo.thread;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ThreadWaitAndNotifyDemo {
    public static void main(String[] args) {
        Producer producer = new Producer();
        producer.start();
        new Consumer("Consumer One", producer).start();
        new Consumer("Consumer Two", producer).start();
        new Consumer("Consumer Three", producer).start();
        new Consumer("Consumer Four", producer).start();
    }

    static class Producer extends Thread {
        List<String> messageList = new ArrayList<>();

        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(2000);
                    synchronized (messageList) {
                        String message = String.format("producer message [create time: %s]", LocalDateTime.now());
                        messageList.add(message);
                        System.out.println("Producer " + getName() + " producer a msg: " + message);
                        messageList.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        String getMessage() {
            synchronized (messageList) {
                if (messageList.size() == 0) {
                    try {
                        messageList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return messageList.remove(0);
            }
        }
    }

    static class Consumer extends Thread {
        private Producer producer;

        public Consumer(String name, Producer producer) {
            super(name);
            this.producer = producer;
        }

        @Override
        public void run() {
            while (true) {
                String message = producer.getMessage();
                System.out.println("Consumer " + getName() + " get a msg: " + message);
            }
        }
    }
}
